package com.jake.rabbit.consumer;

import com.jake.rabbit.producer.ResponseMapProducer;
import com.jake.rabbit.service.RabbitRfcService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.jake.common.constant.KeyConstants.*;
import static com.jake.common.constant.QueueConstants.REQUEST_QUEUE;
import static com.jake.common.constant.QueueConstants.RESPONSE_QUEUE;

@Component
@RabbitListener(queues = {REQUEST_QUEUE + 1, REQUEST_QUEUE + 2,
                REQUEST_QUEUE + 3, REQUEST_QUEUE + 4, REQUEST_QUEUE + 5})
public class RequestMapConsumer {

    @Autowired
    private RabbitRfcService rabbitRfcService;

    @Autowired
    private ResponseMapProducer responseMapProducer;

    @RabbitHandler
    public void listenResponseMap(Map<String, Object> requestMap) {
        Map<String, Object> responseMap = rabbitRfcService.getResponseMap(requestMap);
        String requestId = (String) requestMap.get(REQUEST_ID);
        int requestQueueNumber = (int) requestMap.get(REQUEST_QUEUE_NUMBER);
        if (responseMap == null) {
            responseMapProducer.sendResponseMap(RESPONSE_QUEUE + requestQueueNumber, new HashMap<>(0));
            return;
        }
        responseMap.put(RESPONSE_ID, requestId);
        responseMap.put(RESPONSE_QUEUE_NUMBER, requestQueueNumber);
        responseMapProducer.sendResponseMap(RESPONSE_QUEUE + requestQueueNumber, responseMap);
    }

}
